<template>
  <div class="job-list-container">
    <div class="job-list">
    
      <div class="search-filters">
        <div class="search-box">
          <input 
            v-model="searchKeyword" 
            placeholder="请输入职位关键字" 
            class="search-input"
            @keyup.enter="searchJobs"
          />
          <button @click="searchJobs" class="search-button">搜索</button>
        </div>
        
        <div class="location-filters">
          <select v-model="selectedProvince" @change="onProvinceChange" class="location-select">
            <option value="">请选择省份</option>
            <option v-for="province in provinces" :key="province.code" :value="province.code">
              {{ province.name }}
            </option>
          </select>
          
          <select v-model="selectedCity" @change="onCityChange" class="location-select" :disabled="!selectedProvince">
            <option value="">请选择城市</option>
            <option v-for="city in cities" :key="city.code" :value="city.code">
              {{ city.name }}
            </option>
          </select>
          
          <select v-model="selectedDistrict" class="location-select" :disabled="!selectedCity">
            <option value="">请选择区县</option>
            <option v-for="district in districts" :key="district.code" :value="district.code">
              {{ district.name }}
            </option>
          </select>
          
          <button @click="resetLocation" class="reset-button">重置</button>
        </div>
      </div>
      
      <div v-if="loading" class="loading">加载中...</div>
      <div v-else-if="error" class="error">{{ error }}</div>
      <div v-else>
        <div class="job-items">
          <div 
            v-for="job in jobs" 
            :key="job.job_id" 
            class="job-item"
            @click="goToJobDetail(job)"
          >
            <div class="job-header">
              <h2 class="job-title">{{ job.title }}</h2>
              <div class="job-salary">{{ job.salary_text }}</div>
            </div>
            <div class="job-company">{{ job.company_name }}</div>
            <div class="job-location">{{ job.city }} {{ job.district }}</div>
            <div class="job-details">
              <span class="job-exp">{{ job.exp }}</span>
              <span class="job-edu">{{ job.edu }}</span>
            </div>
            <div class="job-time">{{ formatPublishTime(job.publish_time) }}</div>
          </div>
        </div>
        
        <!-- 分页组件 -->
        <div class="pagination">
          <button 
            :disabled="currentPage === 1" 
            @click="goToPage(currentPage - 1)"
            class="page-btn"
          >
            上一页
          </button>
          
          <span class="page-info">
            第 {{ currentPage }} 页，共 {{ totalPages }} 页
          </span>
          
          <button 
            :disabled="currentPage === totalPages" 
            @click="goToPage(currentPage + 1)"
            class="page-btn"
          >
            下一页
          </button>
        </div>
        
        <div class="job-count">共 {{ count }} 个职位</div>
      </div>
    </div>
  </div>
</template>

<script>
import { JobApi } from '@/utils/api'
import regionData from '@/assets/region-data.json'

export default {
  name: 'JobList',
  data() {
    return {
      jobs: [],
      count: 0,
      loading: true,
      error: null,
      currentPage: 1,
      pageSize: 10,
      searchKeyword: '',
      selectedProvince: '',
      selectedCity: '',
      selectedDistrict: '',
      provinces: [],
      cities: [],
      districts: []
    };
  },
  computed: {
    totalPages() {
      return Math.ceil(this.count / this.pageSize);
    }
  },
  async mounted() {
    this.provinces = regionData;
    await this.fetchJobs();
  },
  methods: {
    async fetchJobs() {
      try {
        this.loading = true;
        const params = {
          page: this.currentPage,
          size: this.pageSize
        };
        
        if (this.searchKeyword) {
          params.keyword = this.searchKeyword;
        }
        
        // 根据选择的地区设置查询参数
        let cityName = '';
        if (this.selectedDistrict) {
          const district = this.districts.find(d => d.code === parseInt(this.selectedDistrict));
          cityName = district ? district.name : '';
        } else if (this.selectedCity) {
          const city = this.cities.find(c => c.code === parseInt(this.selectedCity));
          cityName = city ? city.name : '';
        } else if (this.selectedProvince) {
          const province = this.provinces.find(p => p.code === parseInt(this.selectedProvince));
          cityName = province ? province.name : '';
        }
        
        // 去掉城市名称中的"市"字
        if (cityName) {
          if (cityName.endsWith('市')) {
            cityName = cityName.slice(0, -1);
          }
          params.city = cityName;
        }
        
        const response = await JobApi.getJobList(params);
        
        this.jobs = response.data;
        this.count = response.count;
        this.error = null;
      } catch (err) {
        this.error = '获取职位列表失败';
        console.error('Failed to fetch jobs:', err);
      } finally {
        this.loading = false;
      }
    },
    formatPublishTime(publishTime) {
      const date = new Date(publishTime);
      return date.toLocaleDateString('zh-CN');
    },
    async goToPage(page) {
      if (page >= 1 && page <= this.totalPages) {
        this.currentPage = page;
        await this.fetchJobs();
      }
    },
    goToJobDetail(job) {
      // 打开职位详情页面
      if (job.job_url) {
        window.open(job.job_url, '_blank');
      }
    },
    searchJobs() {
      this.currentPage = 1;
      this.fetchJobs();
    },
    onProvinceChange() {
      this.selectedCity = '';
      this.selectedDistrict = '';
      this.districts = [];
      
      if (this.selectedProvince) {
        const province = this.provinces.find(p => p.code === parseInt(this.selectedProvince));
        if (province && province.list) {
          // 对于直辖市（如北京、上海等），省下面直接是市辖区
          // 对于其他省份，省下面直接是城市
          if (province.list[0] && province.list[0].list) {
            // 这是直辖市的情况，省->市->区
            this.cities = province.list;
          } else {
            // 这是普通省份的情况，省->市
            this.cities = province.list;
          }
        } else {
          this.cities = [];
        }
      } else {
        this.cities = [];
      }
      
      this.searchJobs();
    },
    onCityChange() {
      this.selectedDistrict = '';
      
      if (this.selectedCity) {
        const city = this.cities.find(c => c.code === parseInt(this.selectedCity));
        // 检查这个城市是否有下级区县
        if (city && city.list && city.list.length > 0) {
          this.districts = city.list;
        } else {
          this.districts = [];
        }
      } else {
        this.districts = [];
      }
      
      this.searchJobs();
    },
    resetLocation() {
      this.selectedProvince = '';
      this.selectedCity = '';
      this.selectedDistrict = '';
      this.cities = [];
      this.districts = [];
      this.searchJobs();
    }
  }
};
</script>

<style scoped>
.job-list-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.job-list {
  padding: 20px 0;
}

.job-list h1 {
  text-align: center;
  margin-bottom: 20px;
}

.search-filters {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 8px;
}

.search-box {
  display: flex;
  margin-bottom: 15px;
  gap: 10px;
}

.search-input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.search-button, .reset-button {
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.search-button:hover, .reset-button:hover {
  background-color: #0056b3;
}

.location-filters {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.location-select {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  background-color: white;
}

.location-select:disabled {
  background-color: #f0f0f0;
  cursor: not-allowed;
}

.loading, .error {
  text-align: center;
  padding: 20px;
}

.error {
  color: red;
}

.job-items {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.job-item {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.job-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.job-title {
  margin: 0;
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.job-salary {
  font-weight: bold;
  color: #ff6600;
}

.job-company {
  font-size: 16px;
  color: #666;
  margin-bottom: 5px;
}

.job-location {
  font-size: 14px;
  color: #999;
  margin-bottom: 10px;
}

.job-details {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
}

.job-exp, .job-edu {
  background-color: #f0f0f0;
  padding: 3px 8px;
  border-radius: 4px;
  font-size: 12px;
  color: #666;
}

.job-time {
  font-size: 12px;
  color: #999;
}

.job-count {
  text-align: center;
  margin-top: 20px;
  color: #666;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  margin: 30px 0;
}

.page-btn {
  padding: 8px 16px;
  background-color: #f0f0f0;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.page-btn:hover:not(:disabled) {
  background-color: #e0e0e0;
}

.page-btn:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

.page-info {
  font-size: 14px;
  color: #666;
}

@media (max-width: 768px) {
  .search-box {
    flex-direction: column;
  }
  
  .location-filters {
    flex-direction: column;
  }
  
  .search-button, .reset-button, .location-select {
    width: 100%;
  }
}
</style>